package com.lcp.se.controller;

import com.lcp.se.entity.result.Result;
import com.lcp.se.entity.vo.UploadFileInfo;
import com.lcp.se.service.MinioService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 文件上传下载
 *
 * @author lcp
 * @date 2020/7/20 20:31
 */
@Slf4j
@RestController
@RequestMapping(value = "/oss", method = {RequestMethod.GET, RequestMethod.POST})
public class MinioController {

    @Resource
    private MinioService minioService;

    /**
     * 文件上传
     *
     * @param file 上传文件的名称
     * @param bucketName 要存储的位置
     * @param openId 用户openId
     * @return 上传结果
     */
    @ResponseBody
    @PostMapping("/upload")
    public Result<UploadFileInfo> upload(@RequestParam(name = "file") MultipartFile file,
                                              @RequestParam(name = "fileProp") String bucketName,
                                              @RequestHeader(value = "openId", required = false) String openId) {
        if (file == null || file.getSize() == 0) {
            return Result.failure("上传文件不能为空");
        }
        long start = System.currentTimeMillis();
        // Result<Map<String, String>> result = minioService.upload(file, openId, bucketName);
        Result<UploadFileInfo> result = minioService.upload(file, openId, bucketName);
        log.info("耗时：" + (System.currentTimeMillis() - start));
        return result;
    }

    /**
     * 文件下载
     *
     * @param fileName 要下载的文件名
     */
    @RequestMapping("/download")
    public void download(HttpServletResponse response,
                         @RequestParam(name = "fileName") String fileName,
                         @RequestParam(name = "fileProp") String bucketName) {
        minioService.download(response, fileName, bucketName);
    }

    /**
     * 删除文件
     *
     * @param fileName 要删除的文件名
     * @return 删除结果
     */
    @RequestMapping("/delete")
    public Result<Object> delete(@RequestParam(name = "fileName") String fileName,
                                 @RequestParam(name = "fileProp") String bucketName) {
        return minioService.delete(fileName, bucketName);
    }

}
